package com.example.scaletest.activity;

import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.view.View;
import android.view.Window;
import android.widget.*;
import com.example.scaletest.R;
import com.example.scaletest.batch.BatchService;
import com.example.scaletest.bean.BatchData;
import com.example.scaletest.bean.BindData;
import com.example.scaletest.bean.ProductData;
import com.example.scaletest.db.DataDao;
import com.example.scaletest.scanner.CaptureActivity;
import org.json.JSONArray;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

public class MainActivity extends Activity implements View.OnClickListener{
    private ImageView image_deviceScan;
    private ImageView image_goodsScan;
    private EditText device;
    private EditText goods;
    private Spinner batch;
    private Spinner product;
    private LinearLayout bind;
    private LinearLayout download;// 为什么是linearlayout
    private DataDao dataDao;
    private String batchId ="";
    private String productId = "";
    private List<ProductData> productList;
    private List<BatchData> batchList;
    private UpdateUIBroadcastReceiver broadcastReceiver;
    /**
     * Called when the activity is first created.
     */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        setContentView(R.layout.main);
        dataDao = DataDao.getInstance(this);  // 设么意思
        image_deviceScan = (ImageView) findViewById(R.id.deviceScan);
        image_deviceScan.setOnClickListener(MainActivity.this);
        image_goodsScan = (ImageView) findViewById(R.id.goodsScan);
        image_goodsScan.setOnClickListener(MainActivity.this);
        bind = (LinearLayout) findViewById(R.id.bind);
        bind.setOnClickListener(MainActivity.this);
        download = (LinearLayout)findViewById(R.id.download);
        download.setOnClickListener(MainActivity.this);
        device = (EditText) findViewById(R.id.device);
        goods = (EditText) findViewById(R.id.goods);
        batch = (Spinner) findViewById(R.id.batch);
        batch.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                String item = (String) batch.getSelectedItem();
                for (int i=0; i<batchList.size();i++){
                    if(item==batchList.get(i).getName()){
                        batchId=batchList.get(i).getbatchId();
                    }
                }
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {

            }
        });
        product = (Spinner)findViewById(R.id.product);
        product.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                String item = (String)product.getSelectedItem();
                for (int i = 0; i<productList.size(); i++){
                    if(item == productList.get(i).getItem()){
                        productId = productList.get(i).getProductId();
                    }
                }
                batch.setVisibility(View.INVISIBLE);
                batchId = "";
                Intent intent = new Intent(MainActivity.this,BatchService.class);
                intent.putExtra("request","{\"product_id\":\""+ productId + "\"}");//为什么这么用
                startService(intent);
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {

            }
        });

        registerReceiver();
    }
    public void onClick(View v){
        switch (v.getId()){
            case R.id.deviceScan:
                Intent intent = new Intent(MainActivity.this, CaptureActivity.class);
                startActivityForResult(intent, 1);
                break;
            case R.id.goodsScan:
                intent = new Intent(MainActivity.this, CaptureActivity.class);
                startActivityForResult(intent,2);
                break;
            case R.id.download:
                intent = new Intent(MainActivity.this,BatchService.class);
                String firm= LoginActivity.firm_id;
                intent.putExtra("request","{\"firm_id\":\""+ firm + "\"}");
               // intent.putExtra("request","{\"firm_id\":\"1\"}");
                product.setVisibility(View.INVISIBLE);
                batch.setVisibility(View.INVISIBLE);
                batchId = "";
                Toast.makeText(this,"下载中",Toast.LENGTH_SHORT).show();
                startService(intent);
                break;
            case R.id.bind:
                String device_id = device.getText().toString();
                String goods_id = goods.getText().toString();
                if (batchId.isEmpty()){
                    Toast.makeText(MainActivity.this,"请先下载产品表并选择批次",Toast.LENGTH_SHORT).show();
                }else{
                    if(device_id.isEmpty() || goods_id.isEmpty()) {
                        Toast.makeText(MainActivity.this,"请扫描设备ID或商品ID",Toast.LENGTH_SHORT).show();
                    }else{
                        BindData bindData = new BindData();
                        dataDao.deleteBindData();
                        bindData.setBatchId(batchId);
                        bindData.setDeviceId(device_id);
                        bindData.setGoodsId(goods_id);
                        dataDao.addBindData(bindData);
                        intent = new Intent(MainActivity.this, NetWorkService.class);
                       // intent.putExtra("request","{\"firm_id\":\"1\"}");
                      String firm2= LoginActivity.firm_id;
                        intent.putExtra("request","{\"firm_id\":\""+ firm2 + "\"}");
                        startService(intent);
                    }
                }
                break;
            default:

        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data){
        switch (requestCode){
            case 1:
                if (resultCode == RESULT_OK){
                     device.setText(data.getStringExtra("result"));
                }
                break;
            case 2:
                if(resultCode == RESULT_OK){
                    goods.setText(data.getStringExtra("result"));
                }
                break;
            default:
        }
    }
    public void registerReceiver(){
        IntentFilter filter = new IntentFilter();
        filter.addAction("ACTION_UPDATE_UI");
        broadcastReceiver = new UpdateUIBroadcastReceiver();
        registerReceiver(broadcastReceiver,filter);
    }

    private class UpdateUIBroadcastReceiver extends BroadcastReceiver{

        @Override
        public void onReceive(Context context, Intent intent){

            String jsonData  = intent.getExtras().getString("jsonData");
            if (jsonData.indexOf("productName") != -1){
                updateProduct(jsonData);
            }else if(jsonData.indexOf("batchName") != -1){
                updateBatch(jsonData);
            }
        }
    }

    public void updateProduct(String jsonData){
        List<String> list;
        list = new ArrayList<>();
        try{
            productList = new ArrayList<>();
            JSONObject jsonList = new JSONObject(jsonData);
            JSONArray jsonArray = new JSONArray(jsonList.getString("productlist"));
            productId = jsonArray.getJSONObject(0).getString("productId");
            for(int i = 0; i < jsonArray.length(); i++) {
                JSONObject jsonObject = jsonArray.getJSONObject(i);
                ProductData productData = new ProductData();
                productData.setItem(jsonObject.getString("productName"));
                list.add(productData.getItem());
                productData.setProductId(jsonObject.getString("productId"));
                productList.add(productData);
            }
        }catch (Exception e){
            e.printStackTrace();
        }
        ArrayAdapter<String> arrayAdapter;
        arrayAdapter = new ArrayAdapter<>(MainActivity.this,android.R.layout.simple_spinner_item, list);
        product.setAdapter(arrayAdapter);
        product.setVisibility(View.VISIBLE);

    }

    public void updateBatch(String jsonData){
        List<String> list;
        list = new ArrayList<>();
        try{
            batchList=new ArrayList<>();
            JSONObject jsonList = new JSONObject(jsonData);
            JSONArray jsonArray = new JSONArray(jsonList.getString("batchList"));
            batchId = jsonArray.getJSONObject(0).getString("batchId");
            for(int i = 0; i< jsonArray.length(); i++){
                JSONObject jsonObject = jsonArray.getJSONObject(i);
                BatchData batch = new BatchData();
                batch.setName(jsonObject.getString("batchName"));
                list.add(jsonArray.getJSONObject(i).getString("batchName"));
                batch.setbatchId(jsonObject.getString("batchId"));
                batchList.add(batch);
            }
        }catch (Exception e){
            e.printStackTrace();
        }
        ArrayAdapter<String> arrayAdapter;
        arrayAdapter= new ArrayAdapter<>(MainActivity.this, android.R.layout.simple_spinner_item, list);
        batch.setAdapter(arrayAdapter);
        batch.setVisibility(View.VISIBLE);
    }

    protected void onDestroy(){
        super.onDestroy();
        unregisterReceiver(broadcastReceiver);
    }
}
